package com.ithema.b2b.userconsumer.controller;

import com.ithema.b2b.userconsumer.service.UserService;
import model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "/admin")
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping(value = "/toregister")
    public String toregister() {
        return "register";
    }

    @GetMapping(value = "/tologin")
    public String tologin() {
        return "login";
    }

    @GetMapping(value = "/login")
    public String login(String uname,
                        String upassword,
                        HttpServletRequest request) {
        User user = userService.login(uname);
        if (user != null) {
            if (user.getUpassword().equals(upassword)) {
                HttpSession session = request.getSession(true);
                session.setAttribute("user", user);

                return "redirect:http://localhost:8896/goods/getAll?uaccount=" + user.getUaccount() + "&upassword=" + user.getUpassword();
            }
        }

        System.out.println("登录成功!");
        return "login";
    }

    @GetMapping(value = "/register")
    public String register(HttpServletRequest request, String upassword, String uname, String usex) {
        if (userService.register(upassword, uname, usex) > 0) {
            System.out.print("注册成功");
            return "login";
        }
        System.out.print("注册失败");
        return "register";
    }
}
